//
//  FZComposeView.swift
//  FZSina_Swift
//
//  Created by 李忠 on 7/28/16.
//  Copyright © 2016 FZLZ. All rights reserved.
//

import UIKit
import pop
class FZComposeView: UIView {
    
    var target: UIViewController?
    var buttons: [UIButton] = [UIButton]()
    
    override init(frame: CGRect) {
        super.init(frame: CGRectMake(0, 0, SCREENW, SCREENH))
        setupUI()
        setupLayout()
    }
    
    func setupUI() {
        
        addSubview(bgImageView)
        addChildButton()
        
    }
    
    func setupLayout() {
        bgImageView.snp_makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsetsZero)
        }
    }
    //MARK: 添加btn到View上
    func addChildButton() {
        
        let composeInfos = FZComposeButtonInfo().getButtonInfo()
        
        let btnW: CGFloat = 80
        let btnH: CGFloat = 110
        let margin: CGFloat = (SCREENW - 3 * btnW) / 4
        
        for (index, value) in  composeInfos.enumerate(){
            
            let row = index % 3
            let col = index / 3
            
            let x = btnW * CGFloat(row) + margin * CGFloat(row + 1)
            let y = btnH * CGFloat(col) + margin * CGFloat(col + 1)
            
            let btn = FZComposeButton(frame: CGRectMake(x, y + SCREENH, btnW, btnH))
            
            btn.composeButtonInfo = composeInfos[index]
            
            btn.addTarget(self, action: #selector(clickButton(_:)), forControlEvents: UIControlEvents.TouchUpInside)
            btn.setImage(UIImage(named: value.icon!), forState: UIControlState.Normal)
            btn.setTitle(value.title, forState: UIControlState.Normal)
            btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
            addSubview(btn)
            buttons.append(btn)
            
            
        }
    }
    
    @objc private func clickButton(sender: FZComposeButton){
        
        // 设置动画
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            // 遍历保存按钮数组
            for value in self.buttons {
                

                sender.layer.anchorPoint = CGPointMake(1.0, 1.0)

                // 设置透明度
                value.alpha = 0
                // 判断遍历到的按钮是否是当前点击的按钮
                if value == sender {
                    
                    value.transform = CGAffineTransformMakeScale(2, 2)
                    
                }else {
                    value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                    
                }
    
            }
        }) { (_) -> Void in
            
            UIView.animateWithDuration(0.09, animations: { () -> Void in
                // 遍历保存按钮数组
//                sender.transform = CGAffineTransformScale(sender.transform, 0.2, 0.2)
                sender.transform = CGAffineTransformMakeScale(0.2, 0.2)
                }, completion: { (_) -> Void in
                                        
                    guard let vcName = sender.composeButtonInfo?.nextvc  else{
                        return
                    }
                    
                    guard let pn = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as? String else{
                        return
                    }
                    // 判断class 是否为nil 而且是否可以转成UIViewController.Type
                    // 为什么 “SHComposeViewController” 因为OC中根本没有命名空间 erSwift中有命名空间
                    // 如果Swift中获取自定义类的class [项目名.类名]
                    
                    
                    guard let cn = NSClassFromString("\(pn).\(vcName)") as? UIViewController.Type else {
                        return
                    }
                    // 初始化
                    let tempVc = cn.init()
                    let navC = UINavigationController(rootViewController: tempVc)
                    self.target?.presentViewController(navC, animated: true, completion: { () -> Void in
                        self.removeFromSuperview()
                    })
            })
            
        }
        
    }
    
    
    //MARK: 单击屏幕把自己从父View移除
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.setupButtonsAnim(false)
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.5 * CGFloat(NSEC_PER_SEC))), dispatch_get_main_queue()) {
            
            UIView.transitionWithView(self.target!.view, duration: 0.5, options: .TransitionCrossDissolve, animations: {
                self.removeFromSuperview()
                
            }) { (_) in
            }
            
        }
    }
    //MARK: 显示view
    func showCompose(target: UIViewController)  {
        self.target = target
        target.view.addSubview(self)
        
        UIView.transitionWithView(target.view, duration: 0.5, options: .TransitionCrossDissolve, animations: {
            target.view.addSubview(self)
        }) { (_) in
            self.setupButtonsAnim(true)
        }
    }
    
    //MARK:==========================pop动画==========================
    // 设置buttons动画 (isUp==true 代表向上 显示按钮  false 代表 消失按钮)
    func setupButtonsAnim(isUp: Bool){
        // 距离
        let margin: CGFloat = isUp ? -350 : 350
        // 数组集合
        let set = isUp ? buttons.enumerate() : buttons.reverse().enumerate()
        
        // 遍历按钮数组 分别设置动画
        for (i,value) in set {
            // 设置动画
            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            // 设置tovalue
            anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + margin))
            // 开始时间
            anim.beginTime = CACurrentMediaTime() + Double(i)*0.025
            // 弹性系数
            anim.springBounciness = 10
            // 动画速度
            anim.springSpeed = 8
            value.pop_addAnimation(anim, forKey: nil)
            
        }
    }
    
    //MARK:==========================懒加载==========================
    lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenIMG().applyLightEffect())
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
